package com.situ.crm.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.VO.LayUISelectMVO;
import com.situ.crm.common.ServerResponse;
import com.situ.crm.entity.Permission;
import com.situ.crm.entity.Role;
import com.situ.crm.entity.User;
import com.situ.crm.entity.UserRole;
import com.situ.crm.mapper.PermissionMapper;
import com.situ.crm.mapper.RoleMapper;
import com.situ.crm.mapper.UserMapper;
import com.situ.crm.mapper.UserRoleMapper;
import com.situ.crm.service.IUserService;
import com.situ.crm.util.UserContext;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private RoleMapper RoleMapper;
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public ServerResponse pageList(Integer page, Integer limit) {
		// 1、使用PageHelper插件设置分页
		PageHelper.startPage(page, limit);
		// 2、执行查询
		List<User> list = userMapper.pageList();
		// 3、使用PageInfo对结果进行包装
		PageInfo pageInfo = new PageInfo(list);
		Integer count = (int) pageInfo.getTotal();// 得到总数量

		return ServerResponse.createSuccess("查询成功", count, list);
	}

	@Override
	public ServerResponse insert(User record, String roles) {
		/*
		 * Integer count = userMapper.insert(record); if (count == 1) { return
		 * ServerResponse.createSuccess("添加成功"); } else { return
		 * ServerResponse.createSuccess("添加失败"); }
		 */
		// 将角色插入到数据库
		try {
			Integer count = userMapper.insert(record);
			// 将角色——权限多对多关系放到角色——权限表中
			String[] roleIds = roles.split(",");
			for (String roleId : roleIds) {
				UserRole userRole = new UserRole(record.getId(), Integer.parseInt(roleId));
				userRoleMapper.insert(userRole);
			}
			return ServerResponse.createSuccess();

		} catch (Exception e) {
			return ServerResponse.createSuccess("添加失败");
		}
	}

	@Override
	public ServerResponse deleteById(Integer id) {
		Integer count = userMapper.deleteByPrimaryKey(id);
		if (count == 1) {
			return ServerResponse.createSuccess("删除成功");
		} else {
			return ServerResponse.createSuccess("删除失败");
		}
	}

	@Override
	public User selectById(Integer id) {

		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public ServerResponse selectUserAndRoles(Integer userId) {
		Map<String, Object> map = new HashMap<>();
		// 查询user信息放到map中
		User user = userMapper.selectByPrimaryKey(userId);
		map.put("user", user);
		// 查询所有权限放到map中
		List<Role> roles = RoleMapper.pagelist(new Role());
		List<LayUISelectMVO> list = new ArrayList<>();
		for (Role role : roles) {
			LayUISelectMVO layUISelectMVO = new LayUISelectMVO();
			layUISelectMVO.setId(role.getId());
			layUISelectMVO.setName(role.getSn());
			layUISelectMVO.setStatus(1);
			list.add(layUISelectMVO);
		}
		map.put("allRoles", list);
		// 该角色user对应所有角色ID的数组放在map中
		List<Integer> userSelectRoles = userRoleMapper.selectRolesByUserId(userId);
		map.put("selectIds", userSelectRoles.toArray());

		return ServerResponse.createSuccess("成功", map);
	}

	@Override
	public ServerResponse update(User user, String roles) {
		try {
			// 将角色插入到数据库中
			Integer count = userMapper.updateByPrimaryKey(user);
			// 先删除原有的权限，然后添加新权限
			// 删除
			userRoleMapper.deleteByUserId(user.getId());
			// 添加
			String[] roleIds = roles.split(",");
			for (String roleId : roleIds) {
				UserRole userRole = new UserRole(user.getId(), Integer.parseInt(roleId));
				userRoleMapper.insert(userRole);
			}
			return ServerResponse.createSuccess("修改成功");
		} catch (Exception e) {
			return ServerResponse.createSuccess("修改失败");
		}
	}

	@Override
	public ServerResponse selectCreateMan() {
		List<User> list = userMapper.selectCreateMan();
		System.out.println("list = " + list);

		return ServerResponse.createSuccess("成功", list);

	}

	@Override
	public ServerResponse login(String username, String password, HttpSession session) {
		UserContext.session = session;
		System.out.println("userIMPL的用户名+密码 = " + username + password);
		// user表查询
		User user = userMapper.login(username, password);
		System.out.println("打印一下user = " + user);
		if (user != null) {
			// 把当前用户放到session中
			session.setAttribute(UserContext.USER_IN_SESSION, user);
			// 查询该用户权限 。放到session中
			Integer userId = user.getId();
			List<Permission> permissions = permissionMapper.selectByUserId(userId);
			session.setAttribute(UserContext.PERMISSION_IN_SESSION, permissions);
			return ServerResponse.createSuccess("登录成功");
		}
		return ServerResponse.createSuccess("登录成功");
	}

}
